# 给予其点的坐标，并设置好r的长度，可以做到不错的热图效果

import urllib.request
from pyheatmap.heatmap import HeatMap
import sys
from PIL import Image
from src.utils.txt import Txt

def judge_degree(input_point_txt_path, degree_pro_txt_path, output_point_txt_path, pro_threshold):
    txt = Txt()
    point_list = txt.read_point_txt(input_point_txt_path)
    degree_list = txt.read_pro_txt(degree_pro_txt_path)
    txt.write_point_txt(output_point_txt_path, point_list, degree_list, 1, 2, pro_threshold)


def draw_map(base_img_path, point_txt_path, single_point_range, clickmap_path=None, heatmap_path=None):
    f = open(point_txt_path)
    # testread = f.read()
    sdata_str = f.read()
    sdata = sdata_str.split("\n")
    data = []

    for ln in sdata:
        a = ln.split(",")
        # 因为原来代码只有x,y的坐标，所以a应该只有两个值的情况才对
        # 但生成的txt文件因为带有图片名称，所以有三个值的情况出现
        if len(a) != 2 and len(a) != 3:
            continue
        # 因为第三列是图片名称，这里画热图不需要用到
        a = [int(i) for i in a[:2]]
        data.append(a)

    hm = HeatMap(data)
    if clickmap_path != None:
        hm.clickmap(save_as=clickmap_path, base=base_img_path)
    if heatmap_path != None:
        hm.heatmap(save_as=heatmap_path, base=base_img_path, r=single_point_range)


if __name__ == "__main__":

    # 写入满足阈值要求的某个等级的坐标点
    input_point_txt_path = '../../data/txt/roi/result_roi.txt'
    degree_pro_txt_path = '../../data/txt/roi/Multi_task_degree3.txt'
    output_point_txt_path = '../../data/txt/roi/recognized_roi.txt'
    pro_threshold = 0.99999  # Her2分数某个等级的阈值
    judge_degree(input_point_txt_path, degree_pro_txt_path, output_point_txt_path, pro_threshold)



    point_txt_path = output_point_txt_path  # 点的坐标
    base_img_path = r'..\..\data\result\image\1705206-5_HER2.jpg'  # 底图
    r = 8  # 单个坐标点为圆心的扩散范围
    clickmap_img_path = None
    heatmap_img_path = r'..\..\data\result\image\1705206-5_HER2_heatmap.jpg'

    draw_map(base_img_path, point_txt_path, r, clickmap_path=clickmap_img_path, heatmap_path=heatmap_img_path)